<?php
class LocationsController extends AppController {
	var $name   = 'Locations';
    var $apikey = 'ABQIAAAAy4BJYYvJxo-Pq6h06HShgBTWAvKG72wO6KPcuNpqN_qVWjqt1hQYI0ZkaD7jHXWdMjKWdo2VJGKdbA';
               // 'ABQIAAAA7w-mqWjUiMs0gBaGedbIrxTTsQKzz3cgVj-sa1WqkKeVOXrQAhQ1CaK5ut2s9WwqEXrobQxdrJ3YSA';

    function admin_index () {
        $this->paginate = array(
            'fields' => array(
                'Country.id', 'Country.name', 'Location.id', 'Location.country_id', 'Location.parent_id', 'Location.name',
                'Location.zip', 'Location.latitude', 'Location.longitude', 'Location.timezone', 'Location.ad_post_count',
                'Location.created', 'State.id', 'State.name'
            ),
            'order' => array('Country.name ASC', 'State.name', 'Location.name ASC'),
            'recursive' => 0
        );

        $this->pageTitle = __('Areas Listing', true);
        $this->set('locations', $this->paginate());
    } // admin_index

    function admin_add () {
        if ($this->data) {
            if (!$this->data['Location']['parent_id']) {
                $this->data['Location']['parent_id'] = null;
            }
            if ($this->Location->save($this->data)) {
                //$this->flash(__('New location has been saved.',true), '/admin/locations/add');
                $this->Session->setFlash('<h4>'.__('New location has been saved',true).'</h4>', 'default', array('class'=>'boxSuccess'));
                $this->redirect('/admin/locations/add');
            }
        } else {
            $this->data['Location']['timezone'] = 0;
        }

        App::import('Model', 'Country');
        $country = new Country();
        $parents = $this->Location->find('list', array('conditions'=>array('parent_id'=>null)));

        $this->pageTitle = __('New Location', true);
        $this->javascripts = am($this->javascripts, 'http://maps.google.com/maps?file=api&v=2&key='.$this->apikey.'&sensor=false');
        $this->set('countries', $country->find('list'));
        $this->set('parents', $parents);
        $this->set('timezones', $this->_timezone());
    } // admin_add

    function admin_edit ($id=null, $page=null) {
        if (!$id) {
            $this->flash('<h4>'.__('Missing required id',true).'</h4>', 'index', 5);
        }

        $this->Location->recursive = 0;

        if (empty($this->data)) {
            $this->data = $this->Location->findById($id);
            $this->data['Location']['page'] = $page;
        } else {
            if (!$this->data['Location']['parent_id']) {
                $this->data['Location']['parent_id'] = null;
            }
            if ($this->Location->save($this->data)) {
                $page = ($this->data['Location']['page']) ? '/page:'.$this->data['Location']['page'] : '';
                $this->Session->setFlash('<h4>'.__('The location has been saved',true).'</h4>', 'default', array('class'=>'boxSuccess'));
                $this->redirect('/admin/locations/index'.$page);
            }
        }

        App::import('Model', 'Country');
        $country = new Country();

        $parents = $this->Location->find('list', array('conditions'=>array('parent_id'=>null)));

        $this->pageTitle = __('Edit Location', true);
        $this->javascripts = am($this->javascripts, 'http://maps.google.com/maps?file=api&v=2&key='.$this->apikey.'&sensor=false');
        $this->set('countries', $country->find('list'));
        $this->set('parents', $parents);
        $this->set('timezones', $this->_timezone());
    } // admin_edit

    function admin_delete ($id=null) {
        if (!$id) {
            $this->flash('<h4>'.__('Missing required id',true).'</h4>', 'index', 5);
        }

        $this->Location->del($id);
        $this->flash('<h4>'.__('Location has been deleted',true).'</h4>', 'index', 5);
    } // admin_delete

    function admin_view ($id=null) {
        if (!$id) {
            $this->Session->setFlash('<h4>'.__('Missing required id',true).'</h4>', 'default', array('class'=>'boxError'));
        }
        $this->Location->recursive = 0;
        $this->set('location', $this->Location->findById($id));
    } // admin_view


    function all () {
        $locationId = $this->Cookie->read('User.locationId');
        $locationId = ($locationId) ? $locationId : Configure::read('site.locationId');
        $countryId  = $this->Location->field('country_id', array('id'=>$locationId));

        $adsCount = $this->Location->totalCountryAdvs($countryId);
        $country = $this->Location->getCountry($countryId);
        $name    = urlencode($country['name']);
        $gl      = ($country['code2']) ? '&gl='.$country['code2'] : '';
        $res     = file_get_contents('http://maps.google.com/maps/geo?q='.$name.'&sensor=true&output=csv&oe=utf8'.$gl);
        $data    = @explode(',', $res);

        $params = array(
            'conditions' => 'Location.country_id='.$countryId,
            'recursive'  => -1,
            'fields'     => 'Location.id, Location.parent_id, Location.name, Location.latitude, Location.longitude',
            'order'      => 'Location.name ASC'
        );

        $this->pageTitle   = __('Post & Search Free Classified Ads',true);
        $this->javascripts = am($this->javascripts, 'http://maps.google.com/maps?file=api&v=2&key='.$this->apikey.'&sensor=true');
        $this->set('cities', $this->Location->find('all', $params));
        $this->set('countryL1', $data[2]);
        $this->set('countryL2', $data[3]);
        $this->set('adsCount', $adsCount);
        $this->set('zoom', 4);
    } // all

    function city ($id=null) {
        if (!$id) {
            $this->Session->setFlash('<h4>'.__('Please choose a city listed below',true).'</h4>', 'default', array('class'=>'boxAtt'));
            $this->redirect('/locations/all');
        }

        $location = $this->Location->field('name', array('id'=>$id));

        $this->Cookie->write('User.locationId', $id, false, '1 year');
        $this->Cookie->write('User.location', $location, false, '1 year');
        $this->redirect('/adCategories/index');
    } // city

    function country ($country=null, $id=null) {
        if (!$id) {
            $this->Session->setFlash('<h4>'.__('Please choose a country listed below',true).'</h4>', 'default', array('class'=>'boxAtt'));
            $this->redirect('/');
        }

        $data = $this->Location->find('first', array(
            'conditions' => 'Location.country_id='.$id,
            'fields'     => 'Location.id, Location.name',
            'recursive'  => -1
        ));

        if (count($data['Location']) > 0) {
            $this->Cookie->write('User.locationId', $data['Location']['id'], true, '1 year');
            $this->Cookie->write('User.location', $data['Location']['name'], true, '1 year');
            $this->redirect('/locations/all');
        }

        $this->redirect('/');
    } // country

    function geocoding () {
        Configure::write('debug', 0);

        $form = $this->params['form'];
        $json = array();
        $gl   = $q = '';
        $a    = 5;

        if ($form['country']) {
            App::import('Model', 'Country');
            $country = new Country();
            $iso2    = $country->field('code2', array('country.id ='=>$form['country']));
            if ($iso2) {
                $gl = '&gl='.$iso2;
            }
        }
        if ($form['area']) { // detail with area
            $q = $form['area'];
            $a = ($form['state']) ? 10 : $a;
        }
        if ($form['state']) {
            $this->Location->id = $form['state'];
            $s = $this->Location->field('name');
            $q = ($q) ? $q.', '.$s : $s;
        }

        $response = file_get_contents('http://maps.google.com/maps/geo?q='.urlencode($q).'&sensor=true&output=csv&oe=utf8'.$gl);
        $d = @explode(',', $response);

        if (is_array($d) && count($d) > 0) {
            header('X-JSON: { status:1, accuracy:'.$a.', latitude:'.$d[2].', longitude:'.$d[3].', s:"'.$q.'" }');
        } else {
            header('X-JSON: { status:-1 }');
        }

        $this->set('json', $json);
        $this->render(false, 'json');
    } // geocoding


    function _timezone () {
        $timezone = array(
            -12 => '(GTM-12:00)',
            -11 => '(GTM-11:00)',
            -10 => '(GTM-10:00)',
            -9  => '(GTM-9:00)',
            -8  => '(GTM-8:00)',
            -7  => '(GTM-7:00)',
            -6  => '(GTM-6:00)',
            -5  => '(GTM-5:00)',
            -4  => '(GTM-4:00)',
            '-4.5' => '(GTM-4:30)',
            -3  => '(GTM-3:00)',
            -2  => '(GTM-2:00)',
            -1  => '(GTM-1:00)',
            0   => '(GTM)',
            1   => '(GTM+1:00)',
            2   => '(GTM+2:00)',
            3   => '(GTM+3:00)',
            4   => '(GTM+4:00)',
            5   => '(GTM+5:00)',
            6   => '(GTM+6:00)',
            7   => '(GTM+7:00)',
            8   => '(GTM+8:00)',
            9   => '(GTM+9:00)',
            10  => '(GTM+10:00)',
            11  => '(GTM+11:00)',
            12  => '(GTM+12:00)',
            13  => '(GTM+13:00)'
        );

        return $timezone;
    } // _timezone
} // LocationsController
?>